package com.innovation.ic.im.end.base.thread.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.im.end.base.handler.im_erp9.RabbitMqHandler;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.RabbitMqConstants;
import com.innovation.ic.im.end.base.pojo.enums.ErpAccountStatusEnum;
import com.innovation.ic.im.end.base.pojo.im_erp9.AccountAddPojo;
import com.innovation.ic.im.end.base.service.erp9_sqlserver.Erp9AdminsService;
import com.innovation.ic.im.end.base.service.im_erp9.AccountService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.value.config.RabbitMqParamConfig;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc   监听erp账号状态变更队列
 * @author linuo
 * @time   2022年10月17日10:59:23
 */
public class ListenErpAccountStatusEditQueueThread extends AbstractThread implements Runnable{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /** erp交换机 */
    private String exchange;

    public ListenErpAccountStatusEditQueueThread(Channel channel, String exchange, AccountService accountService, Erp9AdminsService erp9AdminsService, RabbitMqHandler rabbitMqHandler, RabbitMqParamConfig rabbitMqParamConfig, ThreadPoolManager threadPoolManager) {
        this.channel = channel;
        this.exchange = exchange;
        this.accountService = accountService;
        this.erp9AdminsService = erp9AdminsService;
        this.rabbitMqHandler = rabbitMqHandler;
        this.rabbitMqParamConfig = rabbitMqParamConfig;
        this.threadPoolManager = threadPoolManager;
    }

    @SneakyThrows
    @Override
    public void run() {
        String routingKey = RabbitMqConstants.ERP_EDIT_ADMIN_STATUS_QUEUE;
        String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.queueDeclare(queue, true, false, false, null);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    JSONObject jsonObject = JSON.parseObject(bodyString);
                    if(jsonObject != null && !jsonObject.isEmpty()){
                        // 获取消息名称
                        String msgName = jsonObject.getString(RabbitMqConstants.MESSAGE_NAME_FIELD);
                        if(!msgName.equals(RabbitMqConstants.ERP_EDIT_ADMIN_STATUS_QUEUE)){
                            logger.info("mq消息中的方法为:[{}],与当前监听方法:[{}]不一致,不进行后续处理", msgName, RabbitMqConstants.ERP_EDIT_ADMIN_STATUS_QUEUE);
                            return;
                        }

                        // 获取消息体
                        JSONObject json = (JSONObject) jsonObject.get(RabbitMqConstants.MESSAGE_BODY_FIELD);

                        List<AccountAddPojo> accountList = new ArrayList<>();
                        if(json != null && !json.isEmpty()){
                            // 状态(200 启用、500 禁用)
                            Integer status = json.getInteger(RabbitMqConstants.STATUS_FIELD);

                            // 启用
                            if(status.equals(ErpAccountStatusEnum.ENABLE.getCode())){
                                // 账号id数组字段
                                JSONArray jsonArray = (JSONArray) json.get(RabbitMqConstants.ADMIN_IDS_FIELD);
                                List<String> list = JSONObject.parseArray(jsonArray.toJSONString(),  String.class);
                                if(list.size() > 0){
                                    // 通过账号id集合批量获取账号信息
                                    ServiceResult<List<AccountAddPojo>> serviceResult = erp9AdminsService.getAccountInfosByAdminIdList(list);
                                    accountList = serviceResult.getResult();
                                }
                            }
                        }

                        // 处理修改账号状态的mq数据
                        ServiceResult<List<String>> serviceResult = accountService.handleEditAccountStatusRabbitMqData(json, accountList);
                        List<String> updateInfoGroupIdList = serviceResult.getResult();

                        // 推送mq消息给前端更新组织机构数据
                        SendRabbitMqMsgUpdateTreeNodeThread sendRabbitMqMsgUpdateTreeNodeThread = new SendRabbitMqMsgUpdateTreeNodeThread(updateInfoGroupIdList, rabbitMqHandler, rabbitMqParamConfig, accountService);
                        threadPoolManager.execute(sendRabbitMqMsgUpdateTreeNodeThread);
                    }
                    logger.info("erp账号状态变更队列处理结束");
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}